package com.example.imtoken.modules.main.wallet.details

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.entitys.http.PricesEntity
import com.example.imtoken.room.schema.WalletAddressSchema
import kotlinx.coroutines.launch

class WalletDetailsViewModel : BaseViewModel() {

    private val walletDetailsLiveData = MutableLiveData<WalletAddressSchema>()
    fun setWalletDetailsLiveData(walletAddressSchema: WalletAddressSchema) {
        walletDetailsLiveData.value = walletAddressSchema
    }

    fun getWalletDetailsLiveData(): LiveData<WalletAddressSchema> {
        return walletDetailsLiveData
    }

    private val _prices = MutableLiveData<Result<PricesEntity>>()
    val prices: LiveData<Result<PricesEntity>>
        get() = _prices

    fun getPrices(coin: String? = "eth", token: String? = null) {
        viewModelScope.launch {
            _prices.value = try {
                val response = RetrofitUtils.apiService?.prices(coin, token)
                response?.run {
                    LogUtils.json(data)
                    if (code == 0) {
                        if (data?.isNotEmpty() == true) {
                            Result.success(data)
                        } else {
                            Result.failure(Exception("data is null"))
                        }
                    } else {
                        Result.failure(Exception(msg))
                    }
                }
            } catch (e: Exception) {
                Result.failure(e)
            }
        }
    }

}